import React, {Component} from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import {actions} from "mirrorx";
import {Table, Message, Button, Modal} from "tinper-bee";
import FormList from 'components/FormList';
import AcGrids from 'components/AcEditGrid';
import {ts2Formatter} from 'utils';
const EditGrid = AcGrids.EditGrid;
import cloneDeep from 'lodash.clonedeep';
import moment from 'moment';

import './index.less'

const FormItem = FormList.Item;

class ExpenseRedInk extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }

    ExpenseRedInk = () => {
        let { ExpenseRedInkCallback,rowData:rowDataProps } = this.props;
        let rowDataRed = JSON.parse(sessionStorage.getItem("rowDataRed"));
        // let url = "/occ-fee/fee/expense-summary/pull-ActivityScheme";
        let List;
        let data = rowDataProps;
        if(rowDataRed) {
            data.confirmSon = rowDataRed;
        }
        if(data) {
            List = cloneDeep(data).confirmSon.map(item=> {
                //原先的确认金额，如果全额红冲即全额取原本的税额和不含税额
                let preConfirmAmount = parseFloat(item.taxamount + item.notaxamount).toFixed(2);
                if(Math.abs(item.confirmamount) == Math.abs(preConfirmAmount)){
                    item.notaxamount = -item.notaxamount;
                    item.taxamount = -item.taxamount;
                }else{
                    item.notaxamount = parseFloat(item.confirmamount/(1+item.taxNum/100)).toFixed(2);
                    item.taxamount = parseFloat(item.confirmamount-item.notaxamount).toFixed(2);
                }
                item.availableexpenseamount = 0;
                item.expenseamount = item.confirmamount;
                item.availableamount = 0;
                return item;
            })
            data.confirmSon = List;
        }
        data.confirmConnects = [];
        // data.approveTime = moment();
        data.billDate = moment();
        if(!data.redbillcode){
            data.redbillcode = data.billcode;
            delete data.billcode;
        }
        data.persistStatus = "new";
        let errFlag;
        data.confirmSon.map(item=>{
            item.persistStatus = "new";
            if(item.confirmamount == 0) {
                errFlag = "确认金额不能为0"
            }
        })
        if(errFlag) {
            Message.create({ content: errFlag, color: 'warning', duration: 10 });
            return;
        }
        actions.ExpenseConfirmation.save(
            { param: data, callback: (res)=>ExpenseRedInkCallback(res) }
        );
        // actions.ExpenseConfirmation.FeeRedLink({param:data,callback:(res)=>ExpenseRedInkCallback(res)});
    }

    onEditGridChange = (data, childType, operObj, error) => {
        // let { rowData } = this.props;
        // let rowDataRed = cloneDeep(rowData);
        // rowDataRed.confirmSon = data;
        let newData = data.filter(item=> {
            //把确认金额置为空，让用户自己填，以便刷新缓存
            if(item.confirmamount != null){
                return item;
            }
        })
        sessionStorage.setItem("rowDataRed",JSON.stringify(newData || {}));
        // this.setState({rowDataRed:data})
    }

    render() {
        let {showExpenseRedInk,rowData={},ExpenseRedInkCallback} = this.props;
        let columns = [
            {
                title: "费用科目",
                dataIndex: "feeitemName",
                key:"feeitemId",
                disabled:true,
                renderType: "refcomponent",
                width: 100,
                validate: false,
                filedProps: {
                    childType: "retailOrderItems",
                    title: "费用科目",
                    refName: "feeType",
                    constparam:{
                        "EQ_enableState": "1"
                    },
                    fieldName: "feeitemName",
                    reffields: { refpk: "feeitemId", refname: "feeitemName", refcode: "feeitemCode" }
                },
            },
            {
                title: "费用说明",
                dataIndex: "feeremark",
                renderType: "input",
                filedProps: {
                    maxLenght:200,
                },
                disabled:true,
                key: "feeremark",
            },
            {
                title: "发生月份",
                dataIndex: "month",
                key: "month",
                // renderType: "datepicker",
                disabled:true,
                render: (text, record, index) => {
                    return text && ts2Formatter(text,"month");
                },
                filedProps: {
                    format:"YYYY-MM",
                    formatType:"month"
                }
            },
            {
                dataIndex: "confirmamount",
                key: "confirmamount",
                title: "确认金额",
                renderType: "inputnumber",
                edit: true,
                required: false,
            },
            {
                dataIndex: "ext06",
                key: "ext06",
                title: "报销单不含税额",
                renderType: "inputnumber",
                edit: true,
                required: false,
            }
        ]
        
        if(!rowData.confirmSon) return <></>;

        let List = cloneDeep(rowData).confirmSon.filter(item=> {
            if(item.isoppose==0){
                //把部分字段置为空，以便刷新缓存
                item.confirmamount = null;
                item.taxamount = null;
                item.notaxamount = null;
                item.ext06 = null;
                return item;
            }
        })
        return (
            <Modal
            show={showExpenseRedInk}
            size={'xlg'}
            className="getdeal"
            onHide={()=>ExpenseRedInkCallback(false)} >
            <Modal.Header closeButton>
                <Modal.Title>费用红冲（因确认单和报销单税率可能不一致，如不填写则默认红冲报销单参照确认单税率!）</Modal.Title>
            </Modal.Header>

            <Modal.Body>
                <EditGrid
                    className="expanded-table"
                    columns={columns}
                    rowKey={(r, i) => i}
                    hideBtns={{"add":true,"del":true,"copy":true}}
                    onChange={this.onEditGridChange}
                    data={List || []}
                />
               
            </Modal.Body>

            <Modal.Footer>
                <Button onClick={()=>{ExpenseRedInkCallback(false)}} style={{ marginRight: 10 }}><FormattedMessage id="js.Ref.Ref224.0012" defaultMessage="关闭" /></Button>
                <Button onClick={this.ExpenseRedInk} ><FormattedMessage id="js.com.Pas.0005" defaultMessage="确定" /></Button>
            </Modal.Footer>
        </Modal>

        )
    }
}

export default FormList.createForm()(injectIntl(ExpenseRedInk))
